package com.gz.springboot.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;

@Controller
@Slf4j
public class UploadController {

    @GetMapping("/upload.html")
    public String uploadPage() {

        return "upload"; //视图解析
    }

    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("name") String name,
                         @RequestParam("email") String email,
                         @RequestParam("age") Integer age,
                         @RequestParam("job") String job,
                         @RequestParam("header") MultipartFile header,
                         @RequestParam("photos") MultipartFile[] photos) throws IOException {
        log.info("上传的信息: name={} email={} age={} job={} header={} photos={}",
                name, email, age, job, header.getSize(), photos.length);

        String path = ResourceUtils.getURL("classpath:").getPath();

        //如果考虑文件名相同会覆盖的问题，那可以加上UUID和时间来区分存放
        File file = new File(path + "static/images/upload/");
        if (!file.exists()) {
            file.mkdirs();
        }
        //处理头像照片
        if (!header.isEmpty()) {
            String originalFilename = header.getOriginalFilename();
            String filename= UUID.randomUUID().toString()+System.currentTimeMillis();
            header.transferTo(new File(file.getAbsolutePath() + "/" +filename+ originalFilename));
        }

        //处理宠物照片
        if (photos.length > 0) {
            for (MultipartFile photo : photos) {
                if (!photo.isEmpty()) {
                    String originalFilename = photo.getOriginalFilename();
                    String filename= UUID.randomUUID().toString()+System.currentTimeMillis();
                    photo.transferTo(new File(file.getAbsolutePath() + "/" +filename+ originalFilename));
                }
            }
        }

        return "文件上传成功";
    }
}
